#!/usr/bin/env python3

__author__ = 'z.Wick.Tone.Burst'
__doc__ = """."""


import sys
import json
import base64
import getpass
import os.path
import smtplib

from email.header import Header
from email.mime.text import MIMEText
# from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart


class Mail:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
        self.msg = MIMEMultipart('alternative')
        self.msg['subject'] = Header(self.subject, 'utf-8')
        print("> Subject:", self.subject)
        print("> From:", self.account)
        print("> To:", self.dest)

    def text(self, plain):
        txt = MIMEText(str(plain), 'plain')
        self.msg.attach(txt)
        print("+ Text message: %s" % str(plain)[:27],
              "" if len(plain) < 27 else "...")

    def image(self, picture):
        pass

    def attach(self, attachment):
        if not attachment:
            return
        else:
            name = os.path.basename(attachment)
            with open(attachment, 'rb') as f:
                att = MIMEText(f.read(), 'base64', 'utf-8')
            att['Content-Type'] = 'application/octet-stream'
            att["Content-Disposition"] = 'attachment; filename="%s"' % name
            try:
                self.msg.attach(att)
            except:
                print('- *** Failed to attach file "%s"!')
            print('+ File "%s" attached !' % attachment)

    def sendmail(self):
        self.msg['to'] = self.dest
        self.msg['from'] = self.account
        print("* Building secure connection ...")
        try:
            smtp = smtplib.SMTP(self.smtpserver)
            smtp.starttls()
            password = getpass.getpass("Password<%s>: " % self.account)
            smtp.login(self.account.split('@')[0], password)
            print("< Login successed, sending ...")
            smtp.sendmail(self.account, self.dest, self.msg.as_string())
            smtp.quit()
        except smtplib.SMTPAuthenticationError:
            print("- *** Wrong password")
            sys.exit(0)
        print("< Done")



def main(opts, help):
    if not opts.source or not opts.destination:
        help()
        sys.exit(0)
    configure = os.path.join(os.path.dirname(__file__), 'accounts.json')
    with open(configure, 'rt') as f:
        conf = json.load(f)[opts.source]
    mail = Mail(account = conf['account'],
                smtpserver = conf['server'],
                subject = opts.subject,
                dest = opts.destination)
    mail.text(opts.plain)
    mail.attach(opts.attach)
    mail.sendmail()
